<template>
	<div class="tabelContainer">
		<basic-container>
			<avue-crud :option="option" 
				:table-loading="loading" :data="data" :page.sync="page" 
				:permission="permissionList" :search.sync="search" :before-open="beforeOpen" 
				v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" 
				@row-dblclick="handleRowDBLClick" @search-change="searchChange" @search-reset="searchReset" 
				@selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" 
				@refresh-change="refreshChange" @on-load="onLoad">

				<template slot="menuLeft">
					<el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.devicetowerdata_delete" @click="handleDelete">删 除
					</el-button>
				</template>

				<!-- 左侧菜单栏自定义 -->
				<template slot="menuLeft">
					<el-button v-if="tabPosition==='current'" class="refresh-count" size="mini" type="primary" icon="el-icon-refresh" @click="btnRefreshClick()">刷新倒计时 {{countNum}}s
					</el-button>
				</template>

				<!-- 右侧菜单栏自定义 -->
				<template slot="menuRight">
					<el-radio-group id="tabs" v-model="tabPosition" size="mini" type="primary">
						<el-radio-button label="current">实时数据</el-radio-button>
						<el-radio-button label="history">历史数据</el-radio-button>
					</el-radio-group>
				</template>

				<!--自定义列-->
				<template slot="deviceStatus" slot-scope="scope">
					<div v-if="scope.row.isWeightAlarm === 1 || scope.row.isSpeedAlarm === 1 || scope.row.isDipAngleAlarm === 1
             || scope.row.isTopLimitAlarm === 1 || scope.row.isBottomLimitAlarm === 1" class="status-icon warn-status-icon"></div>
					<div v-else class="status-icon normal-status-icon"></div>
				</template>

				<template slot="isWeightAlarmType" slot-scope="scope">
					<div v-if="scope.row.isWeightAlarmType === '报警'" class="warn-status-text">{{scope.row.isWeightAlarmType}}</div>
					<div v-else-if="scope.row.isWeightAlarmType === ''">-</div>
					<div v-else>{{scope.row.isWeightAlarmType}}</div>
				</template>

				<template slot="isSpeedAlarmType" slot-scope="scope">
					<div v-if="scope.row.isSpeedAlarmType === '报警'" class="warn-status-text">{{scope.row.isSpeedAlarmType}}</div>
					<div v-else-if="scope.row.isSpeedAlarmType === ''">-</div>
					<div v-else>{{scope.row.isSpeedAlarmType}}</div>
				</template>

				<template slot="isDipAngleAlarmType" slot-scope="scope">
					<div v-if="scope.row.isDipAngleAlarmType === '报警'" class="warn-status-text">{{scope.row.isDipAngleAlarmType}}</div>
					<div v-else-if="scope.row.isDipAngleAlarmType === ''">-</div>
					<div v-else>{{scope.row.isDipAngleAlarmType}}</div>
				</template>

				<template slot="isTopLimitAlarmType" slot-scope="scope">
					<div v-if="scope.row.isTopLimitAlarmType === '报警'" class="warn-status-text">{{scope.row.isTopLimitAlarmType}}</div>
					<div v-else-if="scope.row.isTopLimitAlarmType === ''">-</div>
					<div v-else>{{scope.row.isTopLimitAlarmType}}</div>
				</template>

				<template slot="isBottomLimitAlarmType" slot-scope="scope">
					<div v-if="scope.row.isBottomLimitAlarmType === '报警'" class="warn-status-text">{{scope.row.isBottomLimitAlarmType}}</div>
					<div v-else-if="scope.row.isBottomLimitAlarmType === ''">-</div>
					<div v-else>{{scope.row.isBottomLimitAlarmType}}</div>
				</template>

				<template slot="runStatus" slot-scope="scope">
					<div v-if="scope.row.runStatus === 0">停止</div>
					<div v-else-if="scope.row.runStatus === 1">上升</div>
					<div v-else-if="scope.row.runStatus === 2">下降</div>
					<div v-else>-</div>
				</template>

				<template slot="weight" slot-scope="scope">
					<div v-if="scope.row.weight === null">-</div>
					<div v-else>{{scope.row.weight}}</div>
				</template>

				<template slot="height" slot-scope="scope">
					<div v-if="scope.row.height === null">-</div>
					<div v-else>{{scope.row.height}}</div>
				</template>

				<template slot="speed" slot-scope="scope">
					<div v-if="scope.row.speed === null">-</div>
					<div v-else>{{scope.row.speed}}</div>
				</template>

				<template slot="windSpeed" slot-scope="scope">
					<div v-if="scope.row.windSpeed === null">-</div>
					<div v-else>{{scope.row.windSpeed}}</div>
				</template>

				<template slot="dipAngle" slot-scope="scope">
					<div v-if="scope.row.dipAngle === null">-</div>
					<div v-else>{{scope.row.dipAngle}}</div>
				</template>

				<template slot="datetime" slot-scope="scope">
					<div v-if="scope.row.datetime === ''">-</div>
					<div v-else>{{scope.row.datetime}}</div>
				</template>

				<!-- 日期搜索自定义 -->
				<template slot-scope="{disabled,size}" slot="datetimeSearch">
					<div class="search-date">
						<el-date-picker v-model="dateFrom" type="date" size="small" placeholder="开始日期" :picker-options="pickerOption" value-format="yyyy-MM-dd"></el-date-picker>
						<div>&nbsp;至&nbsp;</div>
						<el-date-picker v-model="dateTo" type="date" size="small" placeholder="结束日期" :picker-options="pickerOption" value-format="yyyy-MM-dd"></el-date-picker>
					</div>
				</template>
			</avue-crud>

			<!--单击行会跳出的弹窗设置-->
			<el-dialog title="设备详细信息" :visible.sync="dialogVisible" :modal-append-to-body="false" width="45%" top="20vh">
				<el-table :show-header="false" :data="tableData" border :cell-style="columnStyle" style="width: 100%;">
					<el-table-column width="150" prop="prop1"></el-table-column>
					<el-table-column prop="value1"></el-table-column>
					<el-table-column width="150" prop="prop2"></el-table-column>
					<el-table-column prop="value2"></el-table-column>
				</el-table>
			</el-dialog>

		</basic-container>
	</div>
</template>

<script>
	import { getList, getRealTimeData, getDetail, add, update, remove } from "@/api/dust/deviceelevatordata";
	import { mapGetters } from "vuex";
	import { getStore, removeStore } from '@/util/store';
	import { dateFormat } from "@/util/date";

	export default {
		data() {
			return {
				dialogVisible: false, //对话框显隐
				countNum: 10, // 刷新的倒计时变量
				timer: null, // 倒计时定时器管理变量
				tabPosition: 'current', //标签定位在实时数据上

				dateFrom: dateFormat(new Date(), 'yyyy-MM-dd'), // 起止时间值，默认为当天日期
				dateTo: dateFormat(new Date(), 'yyyy-MM-dd'),
				search: {},

				form: {},
				query: {},
				page: {
					pageSize: this.$pageSize,
					currentPage: 1,
					total: 0
				},

				tableData: [{
						prop1: "设备名称",
						value1: "",
						prop2: "设备厂家名称",
						value2: ""
					},
					{
						prop1: "设备类型",
						value1: "",
						prop2: "终端编号",
						value2: ""
					},
					{
						prop1: "驾驶员身份证号",
						value1: "",
						prop2: "",
						value2: ""
					}
				],

				//selectionList: [],
				option: {
					defaultSort: {
						prop: 'datetime',
						order: 'descending' //历史数据按时间倒序排列
					},
					// height: 'auto',
					calcHeight: 30,
					tip: false,
					menu: false,
					searchShow: true,
					searchMenuSpan: 4,
					searchLabelWidth: 100,
					border: true,
					viewBtn: true,
					index: false,
					selection: false,
					dialogClickModal: false,
					column: [{
							label: "项目名称",
							prop: "deptInfoId",
							type: "select",
							dicUrl: "/api/squirrel-ficm/deptinfo/getProjectList",
							props: {
								label: "deptName",
								value: "id"
							},
							hide: true,
							search: true,
							searchSpan: 4,
							searchLabelWidth: 75,
							searchPlaceholder: "请选择",
							rules: [{
								required: true,
								message: "请输入项目名称，中文",
								trigger: "blur"
							}]
						},
						{
							label: "设备名称",
							prop: "deviceName",
							search: true,
							searchSpan: 5,
							searchLabelWidth: 75,
							searchPlaceholder: "请输入",
							rules: [{
								required: true,
								message: "请输入项目名称",
								trigger: "blur"
							}]
						},
						{
							label: "设备状态",
							prop: "deviceStatus",
							slot: true,
							rules: [{
								required: true,
								message: "请输入设备状态",
								trigger: "blur"
							}]
						},
						{
							label: "重量报警",
							prop: "isWeightAlarmType",
							slot: true,
							rules: [{
								required: true,
								message: "请输入重量报警",
								trigger: "blur"
							}]
						},
						{
							label: "速度报警",
							prop: "isSpeedAlarmType",
							slot: true,
							rules: [{
								required: true,
								message: "请输入速度报警",
								trigger: "blur"
							}]
						},
						{
							label: "倾角报警",
							prop: "isDipAngleAlarmType",
							slot: true,
							rules: [{
								required: true,
								message: "请输入倾角报警",
								trigger: "blur"
							}]
						},
						{
							label: "上限位报警",
							prop: "isTopLimitAlarmType",
							slot: true,
							width: "105%",
							rules: [{
								required: true,
								message: "请输入上限位报警",
								trigger: "blur"
							}]
						},
						{
							label: "下限位报警",
							prop: "isBottomLimitAlarmType",
							slot: true,
							width: "105%",
							rules: [{
								required: true,
								message: "请输入下限位报警",
								trigger: "blur"
							}]
						},
						{
							label: "运行状态",
							prop: "runStatus",
							slot: true,
							rules: [{
								required: true,
								message: "请输入运行状态",
								trigger: "blur"
							}]
						},
						{
							label: "重量（千克）",
							prop: "weight",
							width: "105%",
							slot: true,
							rules: [{
								required: true,
								message: "请输入重量",
								trigger: "blur"
							}]
						},
						{
							label: "高度（米）",
							prop: "height",
							width: "105%",
							slot: true,
							rules: [{
								required: true,
								message: "请输入高度",
								trigger: "blur"
							}]
						},
						{
							label: "速度（米/秒）",
							prop: "speed",
							width: "110%",
							slot: true,
							rules: [{
								required: true,
								message: "请输入速度",
								trigger: "blur"
							}]
						},
						{
							label: "风速（米/秒）",
							prop: "windSpeed",
							width: "110%",
							slot: true,
							rules: [{
								required: true,
								message: "请输入风速",
								trigger: "blur"
							}]
						},
						{
							label: "倾角",
							prop: "dipAngle",
							slot: true,
							rules: [{
								required: true,
								message: "请输入倾角",
								trigger: "blur"
							}]
						},
						{
							label: "数据采集时间",
							prop: "datetime",
							type: "datetime",
							format: "yyyy-MM-dd HH:mm:ss",
							valueFormat: "yyyy-MM-dd HH:mm:ss",
							width: 150,
							search: false,
							searchslot: true,
							searchSpan: 10,
							searchLabelWidth: 100,
							slot: true,
							rules: [{
								required: true,
								message: "请输入数据采集时间",
								trigger: "blur"
							}]
						},
					]
				},
				data: [],
			};
		},

		computed: {
			...mapGetters(["permission"]),
			permissionList() {
				return {
					addBtn: this.vaildData(this.permission.devicetowerdata_add, false),
					viewBtn: this.vaildData(this.permission.devicetowerdata_view, false),
					delBtn: this.vaildData(this.permission.devicetowerdata_delete, false),
					editBtn: this.vaildData(this.permission.devicetowerdata_edit, false)
				};
			},
			ids() {
				let ids = [];
				this.selectionList.forEach(ele => {
					ids.push(ele.id);
				});
				return ids.join(",");
			}
		},

		watch: {
			dateFrom() { //日期的起止时间
				if(this.dateFrom) {
					let startDate = new Date(this.dateFrom)
					let endDate = new Date(this.dateTo)
					if(startDate.getTime() > endDate.getTime()) {
						this.dateTo = this.dateFrom
					} else if(endDate.getTime() > startDate.getTime() + 7 * 24 * 60 * 60 * 1000) {
						startDate.setTime(startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
						this.dateTo = dateFormat(new Date(startDate), 'yyyy-MM-dd')
					}
				}
			},
			dateTo() {
				if(this.dateTo) {
					let startDate = new Date(this.dateFrom)
					let endDate = new Date(this.dateTo)
					if(startDate.getTime() > endDate.getTime()) {
						this.dateFrom = this.dateTo
					} else if(endDate.getTime() - 7 * 24 * 60 * 60 * 1000 > startDate.getTime()) {
						endDate.setTime(endDate.getTime() - 7 * 24 * 60 * 60 * 1000)
						this.dateFrom = dateFormat(new Date(endDate), 'yyyy-MM-dd')
					}
				}
			},
			tabPosition(val) {
				if(val === 'current') { //实时数据
					this.page.total = 0; //数据采集时间列以及搜索属性的隐藏
					this.option.column[14].search = false;
					this.onLoad(this.page);
					this.count();
				} else if(val === 'history') { //历史数据
					this.option.column[14].search = true; //数据采集时间列以及搜索属性的显示
					this.onLoad(this.page);
				} else {
					this.data = [];
				}
			}
		},

		created: function() { //页面创建即调用函数count()
			this.count()
		},

		beforeDestroy() {
			removeStore({
				name: 'elevator'
			})
		},

		mounted: function() {
			let elevator = getStore({
				name: 'elevator'
			})
			if(elevator) {
				this.tabPosition = 'history';
				this.onLoad(this.page, this.query);
			}
			// 暴露this
			window.vue = this;
		},

		destroyed: function() { //页面销毁后清除计时器
			window.clearInterval(this.timer);
		},

		methods: {
			rowSave(row, done, loading) {
				add(row).then(() => {
					this.onLoad(this.page);
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					done();
				}, error => {
					loading();
					window.console.log(error);
				});
			},
			rowUpdate(row, index, done, loading) {
				update(row).then(() => {
					this.onLoad(this.page);
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					done();
				}, error => {
					loading();
					console.log(error);
				});
			},
			rowDel(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(row.id);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
					});
			},
			handleDelete() {
				if(this.selectionList.length === 0) {
					this.$message.warning("请选择至少一条数据");
					return;
				}
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(this.ids);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
						this.$refs.crud.toggleSelection();
					});
			},
			beforeOpen(done, type) {
				if(["edit", "view"].includes(type)) {
					getDetail(this.form.id).then(res => {
						this.form = res.data.data;
					});
				}
				done();
			},

			searchReset() {
				this.query = {};
				this.dateFrom = ''; //自定义时间查询，手动清空输入框
				this.dateTo = '';
				this.onLoad(this.page);
			},

			searchChange(params, done) {
				this.query = params;
				this.query['start'] = this.dateFrom; //自定义查询，手动添加键值对
				this.query['end'] = this.dateTo;
				this.page.currentPage = 1;
				this.onLoad(this.page, params);
				done();
			},

			selectionChange(list) {
				this.selectionList = list;
			},
			selectionClear() {
				this.selectionList = [];
				this.$refs.crud.toggleSelection();
			},
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.onLoad(this.page, this.query);
			},

			onLoad(page, params = {}) {
				this.loading = true;
				if(this.tabPosition === 'history') { //历史数据
					this.query['start'] = this.dateFrom;
					this.query['end'] = this.dateTo;
					getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
						const data = res.data.data;
						this.page.total = data.total;
						this.data = data.records;
						this.loading = false;
						this.selectionClear();
					});
				} else if(this.tabPosition === 'current') { //实时数据
					getRealTimeData(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
						const data = res.data.data;
						this.page.total = 0;
						this.data = data;
						this.loading = false;
						this.selectionClear();
					});
				}
				//  this.$refs.crud.doLayout();
			},

			count() { //倒计时控制
				if(this.timer !== null) { //若存在倒计时即清空
					window.clearInterval(this.timer);
				}
				this.countNum = 10;
				this.timer = window.setInterval(() => {
					this.countNum--;
					if(this.countNum <= 0) {
						window.clearInterval(this.timer);
						if(this.tabPosition === 'current') { //重新加载数据列表
							this.count();
							this.onLoad(this.page)
						}
					}
				}, 1000)
			},

			btnRefreshClick() {
				this.onLoad(this.page);
				this.count();
			},

			handleRowDBLClick(row) { //双击行跳出设备详情弹窗
				var col1 = ["deviceName", "deviceType", "idCard"];
				var col2 = ["ownerName", "deviceId", ""];
				for(var i = 0, len = this.tableData.length; i < len; i++) {
					this.tableData[i].value1 = row[col1[i]];
					this.tableData[i].value2 = row[col2[i]]
				}
				this.dialogVisible = true;
			},
		}
	};
</script>

<style lang="scss" scoped>
	#tabs {
		margin-right: 8px
	}

	#status-col {}

	.status-icon {
		width: 18px;
		height: 18px;
		margin: 0 auto;
		border-radius: 50%;
	}

	.search-date {
		display: flex;
		height: 33px;
		line-height: 33px;
	}

	.warn-status-text {
		color: rgba(245, 108, 108, 1);
	}

	.warn-status-icon {
		background-color: rgba(245, 108, 108, 1);
	}

	.normal-status-icon {
		background-color: rgba(103, 194, 58, 1);
	}
</style>
